<?php
namespace app\controller\Admin;

use support\Request;
use support\Response;
use app\model\Order;
use app\model\OrderItem;

class OrderController
{
    /**
     * 获取订单列表
     * @param Request $request
     * @return Response
     */
    public function list(Request $request)
    {
        $query = Order::query();
        
        // 查询条件
        if ($orderNo = $request->input('order_no')) {
            $query->where('order_no', $orderNo);
        }
        if ($cardNo = $request->input('card_no')) {
            $query->where('card_no', $cardNo);
        }
        if ($status = $request->input('status')) {
            $query->where('status', $status);
        }
        if ($scenicSpotId = $request->input('scenic_spot_id')) {
            $query->where('scenic_spot_id', $scenicSpotId);
        }
        if ($startTime = $request->input('start_time')) {
            $query->where('created_at', '>=', $startTime);
        }
        if ($endTime = $request->input('end_time')) {
            $query->where('created_at', '<=', $endTime);
        }

        $data = $query->with(['user', 'scenicSpot', 'items'])
            ->orderBy('order_id', 'desc')
            ->paginate($request->input('limit', 15));

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => $data
        ]);
    }

    /**
     * 获取订单详情
     * @param Request $request
     * @return Response
     */
    public function detail(Request $request)
    {
        $orderId = $request->input('order_id');
        $order = Order::with(['user', 'scenicSpot', 'items.product'])
            ->find($orderId);
            
        if (!$order) {
            return json(['code' => 1, 'msg' => '订单不存在']);
        }

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => $order
        ]);
    }

    /**
     * 取消订单
     * @param Request $request
     * @return Response
     */
    public function cancel(Request $request)
    {
        $orderId = $request->input('order_id');
        $order = Order::find($orderId);
        if (!$order) {
            return json(['code' => 1, 'msg' => '订单不存在']);
        }

        if ($order->status !== 'pending') {
            return json(['code' => 1, 'msg' => '只能取消待支付订单']);
        }

        // 开启事务
        \support\Db::beginTransaction();
        try {
            $order->status = 'cancelled';
            $order->save();

            // 更新订单项状态
            OrderItem::where('order_id', $orderId)
                ->update(['status' => 0]);

            \support\Db::commit();
            return json(['code' => 0, 'msg' => '订单取消成功']);
        } catch (\Exception $e) {
            \support\Db::rollBack();
            return json(['code' => 1, 'msg' => '订单取消失败：' . $e->getMessage()]);
        }
    }

    /**
     * 退款
     * @param Request $request
     * @return Response
     */
    public function refund(Request $request)
    {
        $orderId = $request->input('order_id');
        $order = Order::find($orderId);
        if (!$order) {
            return json(['code' => 1, 'msg' => '订单不存在']);
        }

        if ($order->status !== 'paid' && $order->status !== 'completed') {
            return json(['code' => 1, 'msg' => '订单状态不允许退款']);
        }

        // 开启事务
        \support\Db::beginTransaction();
        try {
            $order->status = 'refunded';
            $order->save();

            // 更新订单项状态
            OrderItem::where('order_id', $orderId)
                ->update(['status' => 0]);

            // TODO: 处理退款逻辑，调用支付接口等

            \support\Db::commit();
            return json(['code' => 0, 'msg' => '退款成功']);
        } catch (\Exception $e) {
            \support\Db::rollBack();
            return json(['code' => 1, 'msg' => '退款失败：' . $e->getMessage()]);
        }
    }

    /**
     * 完成订单
     * @param Request $request
     * @return Response
     */
    public function complete(Request $request)
    {
        $orderId = $request->input('order_id');
        $order = Order::find($orderId);
        if (!$order) {
            return json(['code' => 1, 'msg' => '订单不存在']);
        }

        if ($order->status !== 'paid') {
            return json(['code' => 1, 'msg' => '订单状态不正确']);
        }

        $order->status = 'completed';
        if ($order->save()) {
            return json(['code' => 0, 'msg' => '订单完成']);
        }
        return json(['code' => 1, 'msg' => '操作失败']);
    }
} 